package com.ziyun.erp.common.api.DianWoDa;

import com.alibaba.fastjson.JSONObject;
import com.ziyun.erp.common.utils.HttpClientUtil;
import com.ziyun.erp.common.utils.JsonUtils;
import io.renren.common.utils.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;

import static org.apache.commons.codec.digest.DigestUtils.sha1;

/**
 * 点我达 api
 *
 * @author zh
 * @date 2018/7/2415:41
 */
public class DianWoDaApi {
    /**
     * 日志对象
     */
    private static Logger logger = LoggerFactory.getLogger(DianWoDaApi.class);

    @Value("${dwd.key}")
    private static String KEY;

    @Value("${dwd.url}")
    private static String SECRET;

    @Value("${dwd.secret}")
    private static String URL;

    public static void main(String args[]) {
        DianWoDaApi dianWoDaApi = new DianWoDaApi();

//        DianWoDaOrderSendDto dianWoDaOrderSendDto = new DianWoDaOrderSendDto();
//        dianWoDaOrderSendDto.setOrder_original_id("ZY1116");
//        dianWoDaOrderSendDto.setOrder_create_time(System.currentTimeMillis());
//        dianWoDaOrderSendDto.setOrder_remark("测试订单");
//        dianWoDaOrderSendDto.setOrder_price(5000);
//        dianWoDaOrderSendDto.setCargo_weight(1000);
//        dianWoDaOrderSendDto.setCargo_num(1);
//        dianWoDaOrderSendDto.setCity_code("330100");
//        dianWoDaOrderSendDto.setSeller_id("11111");
//        dianWoDaOrderSendDto.setSeller_name("紫云测试");
//        dianWoDaOrderSendDto.setSeller_mobile("13986101111");
//        dianWoDaOrderSendDto.setSeller_address("湖北省武汉市武汉商务区");
//        dianWoDaOrderSendDto.setSeller_lat(30.315408);
//        dianWoDaOrderSendDto.setSeller_lng(120.165993);
//        dianWoDaOrderSendDto.setConsignee_name("张三");
//        dianWoDaOrderSendDto.setConsignee_mobile("13968041111");
//        dianWoDaOrderSendDto.setConsignee_address("下城区白石路300号史塔克集团顶楼");
//        dianWoDaOrderSendDto.setConsignee_lat(30.315272);
//        dianWoDaOrderSendDto.setConsignee_lng(120.168513);
//        dianWoDaOrderSendDto.setMoney_rider_needpaid(0);
//        dianWoDaOrderSendDto.setMoney_rider_prepaid(0);
//        dianWoDaOrderSendDto.setMoney_rider_charge(5000);
//        dianWoDaOrderSendDto.setTime_waiting_at_seller(300);
//        dianWoDaOrderSendDto.setDelivery_fee_from_seller(500);
//
//        JSONObject json = new JSONObject();
//        json.put("item_name", "名片");
//        json.put("unit", "盒");
//        json.put("quantity", "5");
//        json.put("unit_price", "10000");
//        json.put("discount_price", "5000");
//        json.put("production_time", "0");
//
//        JSONObject json1 = new JSONObject();
//        json1.put("item_name", "复印纸");
//        json1.put("unit", "箱");
//        json1.put("quantity", "5");
//        json1.put("unit_price", "10000");
//        json1.put("discount_price", "5000");
//        json1.put("production_time", "0");
//
//        JSONArray jsonArray = new JSONArray();
//        jsonArray.add(json1);
//        jsonArray.add(json);
//
//        dianWoDaOrderSendDto.setItems(jsonArray.toJSONString());

        //System.out.println(dianWoDaApi.orderSend(dianWoDaOrderSendDto)); //推送订单
        dianWoDaApi.orderAcceptedTest("DWDE1807222110777884");//触发订单状态变化
        /*Map map = new HashMap();
        map.put("order_original_id", "ZY1115");
        map.put("cancle_reason", "测试取消");
        System.out.println(dianWoDaApi.orderCancel(map));*/

//        DianWoDaCostEstimateDto dianWoDaCostEstimateDto = new DianWoDaCostEstimateDto();
//        dianWoDaCostEstimateDto.setCargo_weight(1000);
//        dianWoDaCostEstimateDto.setCity_code("330100");
//        dianWoDaCostEstimateDto.setSeller_id("11111");
//        dianWoDaCostEstimateDto.setSeller_name("紫云测试");
//        dianWoDaCostEstimateDto.setSeller_mobile("13986101111");
//        dianWoDaCostEstimateDto.setSeller_address("湖北省武汉市武汉商务区");
//        dianWoDaCostEstimateDto.setSeller_lat(30.315408);
//        dianWoDaCostEstimateDto.setSeller_lng(120.165993);
//        dianWoDaCostEstimateDto.setConsignee_address("下城区白石路300号史塔克集团顶楼");
//        dianWoDaCostEstimateDto.setConsignee_lat(30.315272);
//        dianWoDaCostEstimateDto.setConsignee_lng(120.168513);
//        System.out.println(dianWoDaApi.costEstimate(dianWoDaCostEstimateDto));

       /* DianWoDaCostEstimateDto dianWoDaCostEstimateDto = new DianWoDaCostEstimateDto();
        dianWoDaCostEstimateDto.setCargo_weight(0);
        dianWoDaCostEstimateDto.setCity_code("330100");
        dianWoDaCostEstimateDto.setSeller_id("2840");
        dianWoDaCostEstimateDto.setSeller_name("杭州鼎诚办公设备有限公司第一分公司");
        dianWoDaCostEstimateDto.setSeller_mobile("18767195619");
        dianWoDaCostEstimateDto.setSeller_address("浙江 杭州市 西湖区 古墩路76号");
        dianWoDaCostEstimateDto.setSeller_lat(30.270298);
        dianWoDaCostEstimateDto.setSeller_lng(120.101815);
        dianWoDaCostEstimateDto.setConsignee_address("浙江 杭州市 西湖区古墩路76号");
        dianWoDaCostEstimateDto.setConsignee_lat(30.270298);
        dianWoDaCostEstimateDto.setConsignee_lng(120.101815);
        logger.info(""+dianWoDaApi.costEstimate(dianWoDaCostEstimateDto));*/

    }


    /**
     * 推送订单
     *
     * @param dianWoDaOrderSendDto
     * @return
     */
    public Map orderSend(DianWoDaOrderSendDto dianWoDaOrderSendDto) {
        Map rsMap = new HashMap();
        try {
            String httpUrl = URL + "/api/v3/order-send.json";

            Map mapParams = JsonUtils.transBean2Map(dianWoDaOrderSendDto);
            if (mapParams == null) {
                throw new RuntimeException("参数转换异常!");
            }

            //处理系统参数 请求接口
            Map map = sysParams(mapParams);
            logger.info("参数: " + map);
            String rs = HttpClientUtil.doPost(httpUrl, map);
            logger.info("result: " + rs);
            if (StringUtil.isEmpty(rs)) {
                throw new RuntimeException("接口请求异常!");
            }

            JSONObject jsonRS = JSONObject.parseObject(rs);

            //获取系统级参数
            String errorCode = jsonRS.getString("errorCode");
            Boolean success = jsonRS.getBoolean("success");

            if (errorCode.equals("0") && success) { //成功单子
                JSONObject resultJson = jsonRS.getJSONObject("result");
                rsMap.put("status", "success");
                rsMap.put("data", resultJson);
                rsMap.put("msg", "推送成功");

            } else { //失败单子
                rsMap.put("status", "error");
                rsMap.put("data", "");
                rsMap.put("msg", jsonRS.getString("message"));
            }

        } catch (Exception e) {
            rsMap.put("status", "error");
            rsMap.put("data", "");
            rsMap.put("msg", e.getMessage());
        }

        logger.info( JSONObject.toJSONString(rsMap) );
        return rsMap;
    }

    /**
     * 取消订单
     *
     * @param mapParams {"order_original_id":"123","cancle_reason","123"}
     * @return
     */
    public Map orderCancel(Map mapParams) {
        Map rsMap = new HashMap();
        try {
            String httpUrl = URL + "/api/v3/order-cancel.json";

            //处理系统参数 请求接口
            Map map = sysParams(mapParams);
            String rs = HttpClientUtil.doPost(httpUrl, map);

            if (StringUtil.isEmpty(rs)) {
                throw new RuntimeException("接口请求异常!");
            }

            JSONObject jsonRS = JSONObject.parseObject(rs);
            System.out.println("取消接口返回原参数:" + jsonRS);
            //获取系统级参数
            String errorCode = jsonRS.getString("errorCode");
            Boolean success = jsonRS.getBoolean("success");

            if (errorCode.equals("0") && success) { //成功单子
                rsMap.put("status", "success");
                rsMap.put("data", "");
                rsMap.put("msg", "取消成功");
            } else {
                rsMap.put("status", "error");
                rsMap.put("data", "");
                rsMap.put("msg", jsonRS.getString("message"));
            }

        } catch (Exception e) {
            rsMap.put("status", "error");
            rsMap.put("data", "");
            rsMap.put("msg", e.getMessage());
        }
        return rsMap;
    }


    /**
     * 运费预估
     *
     * @param dianWoDaCostEstimateDto
     * @return
     */
    public Map costEstimate(DianWoDaCostEstimateDto dianWoDaCostEstimateDto) {
        Map rsMap = new HashMap();
        try {
            String httpUrl = URL + "/api/v3/cost-estimate.json";

            Map mapParams = JsonUtils.transBean2Map(dianWoDaCostEstimateDto);
            if (mapParams == null) {
                throw new RuntimeException("参数转换异常!");
            }

            //处理系统参数 请求接口
            Map map = sysParams(mapParams);
            logger.info("参数: " + map);
            String rs = HttpClientUtil.doPost(httpUrl, map);

            if (StringUtil.isEmpty(rs)) {
                throw new RuntimeException("接口请求异常!");
            }

            JSONObject jsonRS = JSONObject.parseObject(rs);
            logger.info("运费预估接口返回原参数: " + jsonRS);
            //获取系统级参数
            String errorCode = jsonRS.getString("errorCode");
            Boolean success = jsonRS.getBoolean("success");

            if (errorCode.equals("0") && success) { //成功单子
                rsMap.put("status", "success");
                rsMap.put("data", jsonRS.getJSONObject("result").getString("total"));
                rsMap.put("msg", "预估成功");
            } else {
                rsMap.put("status", "error");
                rsMap.put("data", "" );
                rsMap.put("msg", jsonRS.getString("message"));
            }

        } catch (Exception e) {
            rsMap.put("status", "error");
            rsMap.put("data", "");
            rsMap.put("msg", e.getMessage());
        }
        return rsMap;
    }


    /**
     * 接单测试接口
     *
     * @param order_original_id
     */
    public void orderAcceptedTest(String order_original_id) {
        Map map = new HashMap();

        String httpUrl = URL + "/api/v3/order-finish-test.json";

        map.put("order_original_id", order_original_id);
        //处理系统参数 请求接口
        String rs = HttpClientUtil.doPost(httpUrl, sysParams(map));
        System.out.println("rs" + rs);


    }


    /**
     * 组装系统参数
     * log
     *
     * @param mapParams
     * @return
     */
    private Map sysParams(Map mapParams) {
        Map mapParamsNew = new HashMap(mapParams);
        try {
            mapParamsNew.put("pk", KEY);
            mapParamsNew.put("timestamp", System.currentTimeMillis());
            mapParamsNew.put("format", "json");

            /* 生成签名 sig
            对参数名（除系统级参数）进行字典排序，并将参与排序的参数进行拼接成字符串A
            拼接Secret+A+Secret得到字符串B
            对B进行SHA-1加密，结果然后转成16进制字符串并将所有字母转成大写字母得到sig*/

            //对key键值按字典升序排序
            Collection<String> keyset = mapParams.keySet();
            List<String> keyList = new ArrayList<String>(keyset);

            Collections.sort(keyList);

            //拼接字符串A
            String strA = "";
            for (String key : keyList) {
                strA += key + mapParams.get(key);
            }

            // 拼接字符串B
            String strB = SECRET + strA + SECRET;
            //SHA1 加密字符串
            mapParamsNew.put("sig", DigestUtils.sha1Hex(strB).toUpperCase());
            //SHA1 加密字符串
           /* byte[] strSha1 = DigestUtils.sha1(strB.getBytes());;
            logger.info(strSha1.toString());
            System.out.println("测试工具:"+DigestUtils.sha1Hex(strB).toUpperCase());
            for (int i = 0; i <strSha1.length ; i++) {
                System.out.print(strSha1[i]+",");
            }

            //转换16进制 大写字母
            char[] DIGITS_HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
            int l = strSha1.length;
            char[] out = new char[l << 1];
            for (int i = 0, j = 0; i < l; i++) {
                out[j++] = DIGITS_HEX[(0xF0 & strSha1[i]) >>> 4];
                out[j++] = DIGITS_HEX[0x0F & strSha1[i]];
            }

            String sig = new String(out);
            logger.info(sig);*/

        } catch (Exception e) {
            throw new RuntimeException("系统参数组装异常:" + e.getMessage());

        }
        return mapParamsNew;
    }
}
